/**
 * Created by wangdi on 6/11/16.
 */
'use strict';

import React, {Component} from 'react';
import {Text, StyleSheet, View, ScrollView, RefreshControl} from 'react-native';
import HotPanel from '../../component/HotPanel';
import ListViewForHomeTab from '../../component/ListViewForHome';
import ListViewForOtherTab from '../../component/SimpleListView';
import computeTime from '../../util/computeTime';
import theme from '../../config/theme';

export default class HomeTab extends Component {
    constructor(props) {
        super(props);
        this.state = {
            refreshing: true,
            loadedData: false,
            dataBlob: []
        };
    }

    componentDidMount() {
        this._fetchData();
    }

    render() {
        return (
            <ScrollView
                style={{}}
                refreshControl={
                    <RefreshControl
                        refreshing={this.state.refreshing}
                        onRefresh={this._onRefresh.bind(this)}
                        colors={['red','#ffd500','#0080ff','#99e600']}
                        tintColor={theme.themeColor}
                        title="Loading..."
                        titleColor={theme.themeColor}
                    />
                }>
                { this._renderContents() }
            </ScrollView>
        );
    }

    _renderContents() {
        var {tabTag} = this.props;
        if (tabTag === '首页')
            tabTag = '热门推荐';
        else
            tabTag += '热门';

        if (!this.state.refreshing || this.state.loadedData) {
            return (
                <View>
                    <HotPanel title={tabTag} contents={this.state.dataBlob}/>
                    { tabTag === '热门推荐' ?
                        <ListViewForHomeTab contents={this.state.dataBlob}/>
                        :
                        <ListViewForOtherTab contents={this.state.dataBlob}/>
                    }
                </View>
            );
        }
    }

    _onRefresh() {
        this.setState({refreshing: true});
        this._fetchData();
    }

    _getCurrentTime() {
        function convertTime(time) {
            if (time <= 9)
                return '0' + time;
            return time;
        }

        var date = new Date();
        return date.getFullYear() + '-' + convertTime(date.getMonth() + 1) + '-' + convertTime(date.getDate()) + 'T' + convertTime(date.getHours()) + ':' + convertTime(date.getMinutes()) + ':' + convertTime(date.getSeconds() + '.' + date.getMilliseconds() + 'Z');
    }
    _getTag(data) {
        let tagArray = [];
        if(data){
            for(let i in data){
                let title = data[i].title
                tagArray.push(title)
            }
        }else{
            tagArray.push('暂无')
        }
        return tagArray
    }
    _fetchData() {
        var {tabTag} = this.props;
        console.log('首页请求数据-' + tabTag)
        // Android 5562b410e4b00c57d9b94a92
        // 前端 5562b415e4b00c57d9b94ac8
        // iOS 5562b405e4b00c57d9b94a41
        // 产品 569cbe0460b23e90721dff38
        // 设计 5562b41de4b00c57d9b94b0f
        // 工具资源 5562b422e4b00c57d9b94b53
        // 阅读 5562b428e4b00c57d9b94b9d
        // 后端 5562b419e4b00c57d9b94ae2
        // 人工智能 57be7c18128fe1005fa902de
        let tab = '57be7c18128fe1005fa902de'
        let title = ['Android', '前端', 'iOS', '产品', '设计', '工具资源', '阅读', '后端', '人工智能']
        let hash = ['5562b410e4b00c57d9b94a92', '5562b415e4b00c57d9b94ac8','5562b405e4b00c57d9b94a41', '569cbe0460b23e90721dff38','5562b41de4b00c57d9b94b0f', '5562b422e4b00c57d9b94b53',
        '5562b428e4b00c57d9b94b9d', '5562b419e4b00c57d9b94ae2', '57be7c18128fe1005fa902de']
        switch (tabTag) {
            case title[0]:
            tab = hash[0]
            break;
            case title[1]:
            tab = hash[1]
            break;
            case title[2]:
            tab = hash[2]
            break;
            case title[3]:
            tab = hash[3]
            break;
            case title[4]:
            tab = hash[4]
            break;
            case title[5]:
            tab = hash[5]
            break;
            case title[6]:
            tab = hash[6]
            break;
            case title[7]:
            tab = hash[7]
            break;
            case title[8]:
            tab = hash[8]
            break;
        }
        var url = 'https://timeline-merger-ms.juejin.im/v1/get_entry_by_rank?src=web&uid=58f96a731b69e6005882de27&device_id=1510821442805&token=eyJhY2Nlc3NfdG9rZW4iOiIzNlZvT0xEdXJKaW11SnFRIiwicmVmcmVzaF90b2tlbiI6ImlKNThYUGYxNlZISEEzamEiLCJ0b2tlbl90eXBlIjoibWFjIiwiZXhwaXJlX2luIjoyNTkyMDAwfQ%3D%3D&limit='+20+'&category=' + tab;
        fetch(url)
            .then((response) => response.json())
            .then((responseData) => {
                console.log(responseData)
                // let data = responseData.data;
                let listData = responseData.d;
                let list = listData.entrylist
                console.log(list)
                var dataBlob = []; //创建数据model数组
/**
 * Objects are not valid as a React child (found: object with keys {ngxCachedTime, ngxCached, title, id}). If you meant to render a collection of children, use an array instead.
 * 使用
 */
                for (let i in list) {
                    let info = {
                        // author: list[i].author,
                        // checkStatus: list[i].checkStatus,
                        // createdAt: list[i].createdAt,
                        // english: list[i].english,
                        // entryView: list[i].entryView,
                        // gfw: list[i].gfw,
                        // hot: list[i].hot,
                        // hotIndex: list[i].hotIndex,
                        // isCollected: list[i].isCollected,
                        // lastCommentTime: list[i].lastCommentTime,
                        // ngxCachedTime: list[i].ngxCachedTime,
                        // objectId: list[i].objectId,
                        // original: list[i].original,
                        // originalUrl: list[i].originalUrl,
                        // rankIndex: list[i].rankIndex,
                        // subscribersCount: list[i].subscribersCount,
                        // summaryInfo: list[i].summaryInfo,
                        // type: list[i].type,
                        // updatedAt: list[i].updatedAt,
                        // verifyCreatedAt: list[i].verifyCreatedAt,
                        // verifyStatus: list[i].verifyStatus,
                        time: computeTime(list[i].buildTime), //创建时间
                        category: list[i].category, //分类
                        collectionCount: list[i].collectionCount, //点赞人数
                        commentsCount: list[i].commentsCount, //评论地址
                        content: list[i].content, //内容
                        screenshot: list[i].screenshot ? list[i].screenshot : null, //快照
                        tags: this._getTag(list[i].tags), // 标签
                        title: list[i].title, //title
                        user: list[i].user, //作者
                        viewsCount: list[i].viewsCount, //查看人数

                        url: list[i].originalUrl //地址
                    }
                    console.log(info)
                    dataBlob.push(info)
                }

                // for (let i in data) {
                //     let info = {
                //         tags: data[i].tagsTitleArray,
                //         category: data[i].category,
                //         content: data[i].content,
                //         collectionCount: data[i].collectionCount,
                //         title: data[i].title,
                //         user: data[i].user,
                //         url: data[i].url,
                //         time: computeTime(data[i].createdAtString),
                //         commentsCount: data[i].commentsCount,
                //         viewsCount: data[i].viewsCount,
                //         screenshot: data[i].screenshot ? data[i].screenshot : null
                //     }
                //     dataBlob.push(info);
                // }
                console.log(dataBlob?dataBlob.length:'dataBlob='+dataBlob)
                if(dataBlob.length !== 0) {
                    this.setState({
                        dataBlob: dataBlob,
                        loadedData: true,
                        refreshing: false
                    });
                }
            }).done();
    }
}
